from sqlalchemy.orm import Session
from schema import Variety_schema
from model import Variety_model



def get_Variety(db: Session, ID: int):
    return db.query(Variety_model.Variety).filter(Variety_model.Variety.ID == ID).first()


def get_all_Variety(db: Session):
    return db.query(Variety_model.Variety).all()


def delete_Variety(db: Session, ID):
    to_delete = db.query(Variety_model.Variety).filter(Variety_model.Variety.ID == ID)
    deleted = to_delete.delete()
    if deleted == 0:
        return None
    else:
        db.commit()
        return True


def create_Variety(db: Session, Variety: Variety_schema.Variety):
    db_Variety = Variety_model.Variety(
        CropVariety=Variety.CropVariety,
        Code=Variety.Code,
        NationalApprovalNumber=Variety.NationalApprovalNumber,
        AdaptedRegions=Variety.AdaptedRegions,
        CropHistoryID=Variety.CropHistoryID,
    )
    db.add(db_Variety)
    db.commit()
    db.refresh(db_Variety)
    return db_Variety


def update_Variety(db: Session, ID, field_name, new_value):
    db_Variety = db.query(Variety_model.Variety).filter(Variety_model.Variety.ID == ID).first()
    setattr(db_Variety, field_name, new_value)
    db.commit()
    db.refresh(db_Variety)
    return db_Variety
